import editorware from '../../utils/editorMiddleware'
import store from '@/store'
import { Mars3d, initMap } from '../../../utils/initMap'
import request from '@/utils/request'
import { coverageVm } from '../../coverage/utils/coverage.config'
import render from '../../coverage/utils/renderEngine'
import * as turf from '@turf/turf'
// import { map } from 'core-js/core/array'
class contextMenu {
    constructor() {
        this.isPaste = '0' // 1是复制，0是剪切
    }
    /**
     * 标绘图层对象相关*-******************************************************************************************
     */
    /**
     * 右键属性
     */
    property() {
        // let graphic = editorware.rightClickData
        // console.log(graphic)
        // graphic.startEditing()
        // return

        let urlData = JSON.parse(sessionStorage.getItem('urlData'))

        if (urlData && urlData.editor) {
            let graphic = editorware.rightClickData
            // console.log(graphic.options.style)
            if (editorware.isFlyTo) {
                if (graphic.type && graphic.type == 'rectangle') {
                    map.flyToExtent({
                        xmin: graphic.points[0].lng,
                        xmax: graphic.points[1].lng,
                        ymin: graphic.points[0].lat,
                        ymax: graphic.points[1].lat,
                        height: 1000
                    })
                } else {
                    // console.log(graphic.centerPoint)
                    // let aaa = graphic.centerPoint
                    // map.flyToGraphic(graphic, { radius: 1622.1 })
                    map.flyToPoint(graphic.centerPoint, { radius: 1000 })
                }
            }
            store.commit('setSingleProperty', false)
            if (graphic) {
                // console.log(graphic.type)
                if (graphic.type == 'polyline' || graphic.type == 'curve') {
                    graphic.options.style.distance = graphic.distance
                } else {
                    if (!graphic.options.style.area) {
                        graphic.options.style.area = graphic.area
                    }
                    if (graphic.area) {
                        graphic.options.style.area1 = graphic.area
                    }
                    if (graphic.distance) {
                        graphic.options.style.distance = graphic.distance
                    }
                }
                if (!graphic.options.style.name) {
                    graphic.options.style.name = graphic.name
                }
                window.graphicId = graphic.id
                let pData = editorware.treeObj.getNode(graphic.id).parent.data
                // 判断文件夹是否锁定
                if (pData.type == 'folder' && pData.isLocked == 1) {
                    return false
                }
                if (graphicId) {
                    setTimeout(() => {
                        store.commit('setSingleProperty', true)
                        // 对象进入编辑状态
                        graphic.startEditing()
                    })
                }
            }
        }
    }
    /**
     * 删除标绘图层
     */
    removeGraphic() {
        // 获取并删除标绘图层对象
        let graphic = editorware.rightClickData
        if (graphic) {
            request.postForm('api/map/draw/deleteDrawingFile', { drawId: graphic.id }).then(res => {
                if (res.code == 200) {
                    if (graphic.type != 'tif') {
                        graphic.remove()
                    } else {
                        let imgGraphic = [...editorware.coverageMap.values()]
                        imgGraphic.forEach(vg => {
                            if (vg.pid == graphic.id) {
                                map.removeLayer(vg, true)
                            }
                        })
                    }
                    // 删除树形菜单数据
                    if (graphic.id) {
                        let node = editorware.treeObj.getNode(graphic.id)
                        if (node) {
                            editorware.treeObj.remove(node)
                        }
                        // 删除标绘图层集合数据
                        editorware.coverageMap.delete(graphic.id)
                    }
                    if (store.state.singleProperty) {
                        // 关闭属性对话框
                        store.commit('setSingleProperty')
                    }
                    editorware.rightClickData = ''
                    mVm.$message.success('删除成功!')
                }
            })
        }
    }
    /**
     * 剪切或者复制
     */
    copyShearGraphic(type) {
        let graphic = editorware.rightClickData
        // console.log(graphic.name)
        if (type == 'shear') {
            // 剪切--先删除图层
            this.isPaste = '0'
            graphic.remove()
            let node = editorware.treeObj.getNode(graphic.id)
            editorware.treeObj.remove(node)
            // 删除标绘图层集合数据
            // console.log(graphic.id)
            editorware.coverageMap.delete(graphic.id)
            // this.removeGraphic()
        } else {
            this.isPaste = '1'
        }
        // 赋值给中间件
        editorware.copyShearData = graphic
        // console.log(initMap)
    }
    /**
     * tif图层偏移调整
     */
    skewingAmend() {
        let graphic = editorware.rightClickData
        map.flyToExtent({
            xmax: graphic.xmax,
            xmin: graphic.xmin,
            ymax: graphic.ymax,
            ymin: graphic.ymin,
            height: 2000
        })
        store.commit('setSkewingAmend', true)
        store.commit('setamendName', graphic.name)
        store.commit('setamendId', graphic.id)
    }
    /**
     * 瓦片图层偏移调整
     */
    tileAdjustment() {
        let graphic = editorware.rightClickData
        console.log(graphic)
        map.flyToExtent({
            xmax: graphic.options.rectangle.xmax,
            xmin: graphic.options.rectangle.xmin,
            ymax: graphic.options.rectangle.ymax,
            ymin: graphic.options.rectangle.ymin,
            height: 2000
        })
        store.commit('setTileAdjustment', true)
        store.commit('setTileAdjustmentData', graphic.options)
    }
    // pasteGraphic() {
    //     let graphic = editorware.copyShearData
    //     // const lngLat = graphic.points
    //     // 调用渲染函数
    //     // console.log(initMap)
    //     this.renderingLayer(graphic)
    // }
    /**
     *
     * 文件夹相关*****************************************************************************************************
     */
    /**
     * 另存为
     */
    exportFolderJson() {
        let node = editorware.rightClickNode
        let graphic = editorware.rightClickData
        console.log(node)
        // return
        request
            .download('/api/map/draw/saveAsKml', {
                drawId: '',
                folderId: node.data.id
            })
            .then(res => {
                console.log(res)
                if (res) {
                    const blob = res
                    const reader = new FileReader()
                    reader.readAsDataURL(blob)
                    reader.onload = e => {
                        const a = document.createElement('a')
                        a.download = node.data.name + '.kml'
                        // 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
                        a.href = e.target.result
                        document.body.appendChild(a)
                        a.click()
                        document.body.removeChild(a)
                    }
                }
            })
    }
    /**
     * 添加文件夹
     */
    addFolder(val) {
        let baseId = sessionStorage.getItem('baseId')
        let node = editorware.rightClickNode
        if (node && baseId) {
            request.postForm('api/map/baseFolder/newFoldr', { folderName: val, pid: node.data.id, baseId, isEditor: '1', isShow: '1', isLocked: '0' }).then(res => {
                if (res.code == 200) {
                    let data = res.data
                    let addData = {
                        name: data.folderName,
                        pid: data.parentFolder,
                        id: data.id,
                        type: 'folder',
                        editor: data.isEditor ? true : false,
                        show: data.isShow ? true : false,
                        children: [],
                        isLocked: '0'
                    }
                    editorware.treeObj.append(addData, node)
                    editorware.treeObj.setChecked(addData, true, false)
                    node.expanded = true
                    mVm.$message({
                        type: 'success',
                        message: '文件夹添加成功'
                    })
                }
            })
        }
    }
    /**
     * 删除文件夹
     */
    removeFolder() {
        let node = editorware.rightClickNode
        if (node) {
            request.postForm('api/map/baseFolder/deleteFolder', { folderId: node.data.id }).then(res => {
                if (res.code == 200) {
                    editorware.treeObj.remove(node)
                    this.clearGraphicLayer()
                    mVm.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                }
            })
        }
    }
    /**
     * 重命名
     */
    rechristen(val) {
        let node = editorware.rightClickNode
        if (node) {
            request.postForm('api/map/baseFolder/foldrRename', { folderId: node.data.id, folderName: val }).then(res => {
                if (res.code == 200) {
                    node.data.name = val
                    mVm.$message({
                        type: 'success',
                        message: '修改成功!'
                    })
                }
            })
        }
        // node.data.name = val
    }
    /**
     * 删除内容
     */
    removeContent() {
        let node = editorware.rightClickNode
        if (node.childNodes.length > 0) {
            mVm.$confirm('确定要删除该文件夹内的所有文件吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'el-button--primary',
                type: 'warning'
            }).then(() => {
                // 获取当前要删除内容文件夹下的所有标绘数据
                request.get('/api/map/draw/getDrawingAndFolderByFolderId', { folderId: node.data.id }).then(resData => {
                    if (resData.code == 200) {
                        // 数据处理
                        resData.data.draw.forEach(v => {
                            console.log(v)
                            // 删除地图数据
                            let layer = editorware.coverageMap.get(v.id)

                            map.removeLayer(layer, true)
                            // 删除树菜单数据
                            let nodes = editorware.treeObj.getNode(v.id)
                            editorware.treeObj.remove(nodes)
                            // 取消节点选中状态
                            editorware.treeObj.setChecked(node, false, true)
                        })
                    }
                })
                request.postForm('api/map/baseFolder/clearFolderContent', { folderId: node.data.id }).then(res => {
                    if (res.code == 200) {
                        mVm.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                    }
                })
            })
        } else {
            mVm.$alert('该文件夹内没有内容，无需删除')
        }
    }
    /**
     * 锁定文件夹
     * @param isLocked: 锁定状态 1是 0否
     * @param folderId: 文件夹id
     */
    lockFolder() {
        let node = editorware.rightClickNode
        // console.log(node.data)
        request.postForm('api/map/baseFolder/modifyTheLockState', { folderId: node.data.id, isLocked: 1 }).then(res => {
            if (res.code == 200) {
                node.data.isLocked = 1
                if (node.data.children && node.data.children.length > 0) {
                    this.updateFolderLockedType(node.data.children, 1)
                }
                mVm.$message.success('锁定成功')
            }
        })
    }
    /**
     * 解锁文件夹
     */
    unlockFolder() {
        let node = editorware.rightClickNode
        request.postForm('api/map/baseFolder/modifyTheLockState', { folderId: node.data.id, isLocked: 0 }).then(res => {
            if (res.code == 200) {
                node.data.isLocked = 0
                if (node.data.children && node.data.children.length > 0) {
                    this.updateFolderLockedType(node.data.children, 0)
                }
                mVm.$message.success('解除锁定成功')
            }
        })
    }
    /**
     * 修改文件夹锁定状态的递归函数
     */
    updateFolderLockedType(arry, data) {
        arry.forEach(v => {
            if (v.type == 'folder') {
                v.isLocked = data
            }
            if (v.children && v.children.length > 0) {
                this.updateFolderLockedType(v.children, data)
            }
        })
    }
    /**
     * 复制文件夹
     */
    copyShearFolder(type) {
        let node = editorware.rightClickNode
        // 设置当前复制或者剪切的对象
        editorware.copyShearData = node
        // console.log(node)
        // 剪切需要删除当前node
        if (type == 'shear') {
            this.isPaste = '0'
            editorware.treeObj.remove(node)
        } else {
            this.isPaste = '1'
        }
    }
    /**
     * 粘贴文件夹---图层
     */
    pasteFolder() {
        let pasteData = editorware.copyShearData
        // 菜单
        let node = editorware.rightClickNode
        if (pasteData.type) {
            // 标绘对象
            request.postForm('api/map/draw/copyDrawing', { drawId: pasteData.id, folderId: node.data.id, isPaste: this.isPaste }).then(res => {
                if (res.code == 200) {
                    res.data.positions = JSON.parse(res.data.positions)
                    res.data.style = JSON.parse(res.data.style)
                    // 添加数据到树菜单
                    let addNode = {
                        name: res.data.name,
                        pid: res.data.pid,
                        id: res.data.id,
                        type: res.data.type,
                        editor: true,
                        show: Number(res.data.isShow) ? true : false
                    }
                    let appendNodes = editorware.treeObj.getNode(res.data.folderId)
                    editorware.treeObj.append(addNode, appendNodes)
                    if (addNode.show) {
                        editorware.treeObj.setChecked(addNode, true, false)
                    }
                    // 渲染数据到地图
                    render(res.data)
                    mVm.$message({
                        type: 'success',
                        message: '粘贴成功!'
                    })
                }
            })
        } else {
            request.postForm('api/map/baseFolder/copyFolder', { folderId: pasteData.data.id, pid: node.data.id, isPaste: this.isPaste }).then(res => {
                if (res.code == 200) {
                    request.get('/api/map/draw/getDrawingAndFolderByFolderId', { folderId: res.data.pid }).then(resData => {
                        if (resData.code == 200) {
                            // 文件夹处理
                            resData.data.folder.forEach(v => {
                                if (!editorware.treeObj.getNode(v.id)) {
                                    let addNode = {
                                        name: v.folderName,
                                        pid: v.parentFolder,
                                        id: v.id,
                                        type: 'folder',
                                        isLocked: v.isLocked,
                                        editor: true,
                                        show: Number(v.isShow) ? true : false
                                    }
                                    let appendNodes = editorware.treeObj.getNode(v.parentFolder)
                                    editorware.treeObj.append(addNode, appendNodes)
                                }
                            })
                            // 数据处理
                            resData.data.draw.forEach(v => {
                                if (!editorware.treeObj.getNode(v.id)) {
                                    // 添加数据到树菜单
                                    let addNode = {
                                        name: v.name,
                                        pid: v.pid,
                                        id: v.id,
                                        type: v.type,
                                        editor: true,
                                        show: Number(v.isShow) ? true : false
                                    }
                                    let appendNodes = editorware.treeObj.getNode(v.pid)
                                    editorware.treeObj.append(addNode, appendNodes)
                                    if (addNode.show) {
                                        editorware.treeObj.setChecked(addNode, true, false)
                                    }
                                    // 渲染数据到地图
                                    render(v)
                                }
                            })
                        }
                    })
                    mVm.$message({
                        type: 'success',
                        message: '粘贴成功!'
                    })
                }
            })
        }
        // 打开粘贴的目标文件夹
        node.expanded = true
    }
    // // 图层渲染函数
    // renderingLayer(layer, data, callBack) {
    //     let graphic = ''
    //     switch (layer.type) {
    //         case 'circle':
    //             // 圆
    //             graphic = new mars3d.graphic.CircleEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         case 'billboard':
    //             // 图标点
    //             graphic = new mars3d.graphic.BillboardEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         case 'polyline':
    //             // 线
    //             graphic = new mars3d.graphic.PolylineEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         case 'curve':
    //             // 曲线
    //             graphic = new mars3d.graphic.CurveEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         case 'polygon':
    //             // 面
    //             graphic = new mars3d.graphic.PolygonEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         case 'rectangle':
    //             // 矩形
    //             graphic = new mars3d.graphic.RectangleEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         case 'ellipse':
    //             // 椭圆柱体
    //             graphic = new mars3d.graphic.EllipseEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         case 'box':
    //             // 长方体
    //             graphic = new mars3d.graphic.BoxEntity({
    //                 position: layer.coordinate,
    //                 style: layer.style
    //             })
    //             break
    //         default:
    //             console.log(layer.type)
    //     }
    //     graphic.id = data.id
    //     initMap.graphicLayer.addGraphic(graphic)
    //     // graphic.show = true
    //     console.log(layer)
    //     // return
    //     let addData = {
    //         // name: layer.name ? layer.name : `${layer.type}#${editorware.coverageMap.size}`,
    //         name: data.name,
    //         pid: data.folderId,
    //         id: graphic.id,
    //         type: graphic.type,
    //         editor: true,
    //         show: true
    //     }
    //     console.log(editorware.coverageMap)
    //     // return
    //     // editorware.treeObj.append(addData, editorware.treeSelectData)
    //     if (!editorware.coverageMap.get(graphic.id)) {
    //         editorware.coverageMap.set(graphic.id, graphic)
    //     }
    //     // editorware.addCoverageObj(addData)
    //     callBack(addData)
    //     // 绑定右键菜单
    //     let that = this
    //     graphic.on(mars3d.EventType.rightClick, function(a) {
    //         const commitData = {
    //             isShow: true,
    //             X: a.position.x,
    //             Y: a.position.y,
    //             type1: 'layerMenu',
    //             type2: 'layer',
    //             time: new Date().getTime()
    //         }
    //         store.commit('setContextMenu', commitData)
    //         editorware.rightClickData = a.graphic
    //     })
    //     // 绑定点击事件
    //     graphic.on(mars3d.EventType.click, function(a) {
    //         // const commitData = {
    //         //     isShow: true,
    //         //     X: a.position.x,
    //         //     Y: a.position.y,
    //         //     type1: 'layerMenu',
    //         //     type2: 'layer',
    //         //     time: new Date().getTime()
    //         // }
    //         // store.commit('setContextMenu', commitData)
    //         let graphic = editorware.rightClickData
    //         if (graphic) {
    //             graphic.stopEditing()
    //         }
    //         editorware.rightClickData = a.graphic
    //         that.property()
    //     })
    //     // graphic({
    //     //     position: layer.points,
    //     //     style: layer.style
    //     // })
    // }
    // 删除地图图层数据
    clearGraphicLayer() {
        // 清空地图图层数据
        initMap.graphicLayer.clear()
        // 清空map集合数据
        editorware.coverageMap.clear()
        // 从新渲染地图图层数据
        request.get('/api/map/draw/getDrawingByBaseId', { baseId: sessionStorage.getItem('baseId') }).then(res => {
            if (res.code == 200 && res.data.length > 0) {
                res.data.forEach(v => {
                    let addNode = {
                        name: v.name,
                        pid: v.pid,
                        id: v.id,
                        type: v.type,
                        editor: true,
                        show: Number(v.isShow) ? true : false
                    }
                    // console.log(addNode);
                    if (v.style.allTilt) {
                        //刷新批量修改的倾斜坐标计算
                        if (v.type == 'polyline' || v.type == 'curve') {
                            let ctl = parseFloat(v.style.distance) * (parseFloat(v.style.allTilt) * 0.01)
                            v.style.label.text = ctl.toFixed(2) + ' m'
                            v.style.tilt = v.style.allTilt
                        } else if (v.type == 'polygon') {
                            let ctl = parseFloat(v.style.area) * (parseFloat(v.style.allTilt) * 0.01)
                            v.style.label.text = ctl.toFixed(2) + ' m'
                            v.style.tilt = v.style.allTilt
                        }
                    }
                    let pNode = editorware.treeObj.getNode(v.pid)
                    if (pNode) {
                        // editorware.treeObj.append(addNode, pNode)
                        // 设置新添加子菜单为选中状态
                        if (addNode.show) {
                            editorware.treeObj.setChecked(addNode, true, false)
                        }
                        // 渲染数据
                        render(v)
                    }
                })
            }
        })
    }
}
const cMenu = new contextMenu()
export default cMenu
